package com.example.zbh.dsliao.service;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

import com.example.zbh.dsliao.MusicIdle;
import com.example.zbh.dsliao.model.entity.PersonalList;
import com.example.zbh.dsliao.utils.MyEventBus;

import java.io.IOException;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by yaolin on 15/11/24.
 */
public class DliaoService extends Service {


    private MediaPlayer mediaPlayer;
    //我的歌曲列表
    private List<PersonalList> personalLists;
    private int index = 0; //定义当前正在播放的歌曲位置
    private boolean isplay = false;
    private boolean flag = true;
    private Handler handler = new Handler();

    private int random;

    private String modeFlag = "ORDER_MODE";  //播放模式

    //定义一个handler永远刷新进度条
    private Runnable r = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(r, 500);
            if (mediaPlayer != null) {
                EventBus.getDefault().post(new MyEventBus.CurrentIndex(mediaPlayer.getCurrentPosition()));
                //Log.i("test", "DliaoService->CurrentProgress" + mediaPlayer.getCurrentPosition());
                EventBus.getDefault().post(new MyEventBus.MaxProgress(mediaPlayer.getDuration()));
            }

            //发送消息
            //  EventBus.getDefault().post(new MyEventBus.UpDataSeek(mediaPlayer.getCurrentPosition()));

        }
    };


    /**
     * 1.把数据传到服务里(Arrylist)
     * 2.把aidl里的方法写完整,
     * 3.用eventBus把数据传递出去
     */
    public void onEvent(MyEventBus.TestClass testClass) {
        Log.d("DliaoService", testClass.getStrings().get(0));
    }


    public void onEvent(MyEventBus.PlayerMode playerMode) {
        modeFlag = playerMode.getMode();
        Log.i("lanou3g", "接收的Mode:" + modeFlag);
    }


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return musicIdle;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        //handler.postDelayed(r, 500);

        EventBus.getDefault().register(this);

        //初始化
        mediaPlayer = new MediaPlayer();


        //准备完成的监听
        mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                try {
                    musicIdle.play();//准备完成后播放
                } catch (RemoteException e) {
                    e.printStackTrace();
                }

            }
        });

        //播放完成的监听
        mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                if (modeFlag.equals("ORDER_MODE")) {
                    Intent intent = new Intent("com.lanou.player.next");
                    sendBroadcast(intent);
                } else if (modeFlag.equals("RADOM_MODE")) {
                    random = (int) (Math.random() * (19 - 0) + 0);
                    EventBus.getDefault().post(new MyEventBus.RandomMode(random));
                    Intent it = new Intent("com.lanou.player.radomPlay");
                    sendBroadcast(it);
                } else if (modeFlag.equals("SINGLE_MODE")) {
                    Intent it = new Intent("com.lanou.player.singlelay");
                    sendBroadcast(it);
                }
                Log.i("lanou3g", "播放模式:" + modeFlag);

            }
        });
    }


    MusicIdle.Stub musicIdle = new MusicIdle.Stub() {
        //设置网址
        @Override
        public void setUrl(String url) throws RemoteException {
            try {
                handler.removeCallbacks(r);
                mediaPlayer.reset();//重置
                mediaPlayer.setDataSource(url);//设置url
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);//设置音频流
                mediaPlayer.prepareAsync();//异步的准备,准备完成后自动调用准备完成的监听
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        //得到当前进度
        @Override
        public int setCurrentIndex() throws RemoteException {
            return mediaPlayer.getCurrentPosition();
        }

        //得到最大进度
        @Override
        public int getDuration() throws RemoteException {
            return mediaPlayer.getDuration();
        }

        //刷新进度条
        @Override
        public void setProgress(int progress) throws RemoteException {
            mediaPlayer.seekTo(progress);
        }

        //下一首
        @Override
        public void next() throws RemoteException {
            Intent intent = new Intent("com.lanou.player.next");
            sendBroadcast(intent);
        }


        //上一首
        @Override
        public void previous() throws RemoteException {
            Intent intent = new Intent("com.lanou.player.previous");
            Log.i("Sysout", "发送广播");
            //发送广播
            sendBroadcast(intent);

        }


        //播放
        @Override
        public void play() throws RemoteException {
            try {
                handler.removeCallbacks(r);
            } catch (Exception e) {

            }
            mediaPlayer.start();//播放
            handler.postDelayed(r, 500);
        }

        //暂停
        @Override
        public void pause() throws RemoteException {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.pause();
            }

        }

        //停止
        @Override
        public void stop() throws RemoteException {
            if (mediaPlayer.isPlaying()) {
                mediaPlayer.stop();

                mediaPlayer.release();
                mediaPlayer = null;

            }
        }

        //是否正在播放
        @Override
        public boolean getMusicIsPlaying() throws RemoteException {
            return mediaPlayer.isPlaying();
        }

        @Override
        public String datas() throws RemoteException {
            return null;
        }


    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);


//        mediaPlayer.stop();
//        mediaPlayer.release();
//        mediaPlayer = null;

    }
}

